package com.app.utils;

import android.content.Context;
import android.text.TextUtils;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.main.activity.MainTabActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 统计也面从后台进入前台 这个类，必须在固定的包下，类名，方法名都不能变。通过从lib_core中，反射调用
 */
public class AppEnterTongJi implements AsyncRequest {

	public static final String REQUEST_ENTER_USE = "request_enter_use";

	private static AppEnterTongJi mInstance = null;
	private static JSONArray mJsonArray = new JSONArray();

	public static AppEnterTongJi getInstance() {
		if (mInstance == null) {
			mInstance = new AppEnterTongJi();
			initDayJsonArray();
		}
		return mInstance;
	}

	/**
	 * 统计进入使用
	 * 
	 * @param context
	 */
	public void requestEnterUse(Context context) {

		// test
		// clear();//?????????????????????????????????????????????????????????
		// 程序没有启动，不做前后台切换统计
		if (MainTabActivity.getInstance() == null) {
			return;
		}

		if(mJsonArray == null || mJsonArray.length() == 0){
			return;
		}

		// app前后台切换
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("ClientVersion", AppManager.getAppVersionName(context));
			params.put("ClientOSVersion",
					AppManager.getDeviceSdkVersion(context));
			params.put("DeviceModel", AppManager.getDeviceModel(context));
			params.put("DeviceSN", AppManager.getDeviceUniqueId(context));
			params.put("ClientIP", AppManager.getDeviceIpAddress(context));

			String umengChannel = UtilityBase.getAppMetedata(context,
					"UMENG_CHANNEL");
			params.put("AppChannel", umengChannel);

			params.put("Actions", mJsonArray);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getUserBehaviorLogUrl(), map, null, this,
				REQUEST_ENTER_USE, false);
	}

	private void clear() {
		mJsonArray = new JSONArray();
		AppConfig.setConfig(MyApplication.getInstance(),
				Const.CONFIG_APP_ENTER_TONG_JI, "");
	}

	private static void initDayJsonArray() {

		String oldDayString = AppConfig
				.getConfigString(MyApplication.getInstance(),
						Const.CONFIG_APP_ENTER_TONG_JI, "");
		if (!TextUtils.isEmpty(oldDayString)) {
			try {
				mJsonArray = new JSONArray(oldDayString);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param BehaviorType
	 * @param Target
	 *            例如： 被浏览文章的ID； 外部的url
	 */
	public static void clickEvent(int BehaviorType, String Target) {

		// umeng 事件统计
		UmengHelper.CustomEvent(MyApplication.getInstance(),
				String.valueOf(BehaviorType));

		String ActionTime = DateUtilBase.stringFromDate(new Date(),
				DateUtilBase.DATE_ALL_ALL);

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("ActionTime", ActionTime);
			jsonObject.put("BehaviorType", BehaviorType);
			jsonObject.put("Target", Target);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		mJsonArray.put(jsonObject);

		AppConfig.setConfig(MyApplication.getInstance(),
				Const.CONFIG_APP_ENTER_TONG_JI, mJsonArray.toString());
	}

	// ==============================
	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_ENTER_USE)) {
			LogUtilBase.LogD(null, REQUEST_ENTER_USE + "_success");

			clear();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_ENTER_USE)) {
			LogUtilBase.LogD(null, REQUEST_ENTER_USE + "_fail");
		}
	}

}
